package net.skyedu.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

public class IPUtil { 
	/**
	  * 获取客户端IP 
	  * @param request
	  * @return
	*/
	public static String getClientIp(HttpServletRequest request){
		
		  String ip = request.getHeader("X-Forwarded-For");
	      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	          ip = request.getHeader("Proxy-Client-IP");
	      }
	      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	          ip = request.getHeader("WL-Proxy-Client-IP");
	      }
	      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	          ip = request.getHeader("HTTP_CLIENT_IP");
	      }
	      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	          ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	      }
	      if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	          ip = request.getRemoteAddr();
	      }
	      if(ip == null){
			  ip = "192.168.123.321";
		  }
	      return ip;
	} 
    /**
     * 是否外网 
     * @param ip
     * @return
     */
	public static Integer getIpType(String ip)
	{
		Integer ipType;
		Pattern p = Pattern.compile("^((192.168.)|(10.)|(172.16)|(127.0))+[0-9.]+$");		
		if(p.matcher(ip).matches()) {
			ipType = 1;
		}else {
			ipType = 2;
		}
		return ipType;
	}
	
	/**
	 * 动态读取配置文件  用key获取value
	 * @param arg
	 * @return
	 */
	public static String getShortMsg(String key){
		 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		 System.out.println(path);
		 //获取绝对路径，完美解决动态加载properties
	     Properties prop = new Properties();
	     try {
	    	 InputStream in = new FileInputStream(path + "/message.properties");
	    	 System.out.println(path + "/message.properties");
	    	 prop.load(in);
	     }catch (FileNotFoundException e) {
			  e.printStackTrace();
		 }catch (IOException e) {
	    	  e.printStackTrace();
	     }
		 return prop.getProperty(key);
	}
	
	
//	public static void main(String[] args) {
//		Integer ty = getIpType("127.0.0.1");
//		if(ty==1){
//			System.out.println("内网");
//		}else{
//			System.out.println("外网");
//		}
//	}
}